<template>
  <div class="cardArea">
    <!-- 标题 -->
    <div class="cardArea_title">
      <div class="cardArea_title_label"></div>
      <div class="cardArea_title_content">{{ formDefine.name_ + ' - 环节配置' }}</div>
      <a-button class="cardArea_timelimit" type="primary" icon="dashboard" @click="showTimeLimit"> 办结时限 </a-button>
    </div>

    <!-- tab页 -->
    <div class="cardArea_tabs">
      <a-tabs v-model="key" @change="tabChange">
        <!-- 环节表格 -->
        <a-tab-pane key="1">
          <span slot="tab">
            <a-icon type="menu" />
            流程环节
          </span>
          <!-- 环节配置 -->
          <a-table
            :scroll="{ x: 1500, y: 400 }"
            :columns="ucolumns"
            :data-source="udata"
            :pagination="upagination"
            :loading="loading"
            rowKey="id"
            @change="tableChange"
            size="middle"
            :bordered="ubordered"
          >
            <div class="titleBox" slot="title"></div>
            <span slot="serial" slot-scope="text, record, index">
              {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
            </span>
            <!-- 环节名称插槽 -->
            <template slot="nameSlot" slot-scope="text, record">
              {{ text }} <span v-if="record.documentation"> （{{ record.documentation }}）</span>
            </template>

            <span slot="operation" slot-scope="text, record">
              <template>
                <a @click="handleEdit(record)">编辑</a>
              </template>
            </span>
          </a-table>
        </a-tab-pane>
        <!-- 环节组配置 -->
        <a-tab-pane key="2">
          <span slot="tab">
            <a-icon type="appstore" />
            环节组配置
          </span>
          <NodeScat ref="NodeScatRef" v-if="formDefine.key_" :modelKey="formDefine.key_" :formid="formDefine.id" />
        </a-tab-pane>
        <!-- 流程图 -->
        <a-tab-pane key="3">
          <span slot="tab">
            <a-icon type="picture" />
            流程图
          </span>
          <!-- 流程图 -->
          <div class="imgBox">
            <img :src="processimg" :data-original="processimg" />
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
    <!-- 办结时限抽屉 -->
    <a-drawer
      title="办结时限编辑"
      :width="720"
      :visible="visible"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
    >
      <TimeLimit ref="limitRef" @close="onClose"></TimeLimit>
    </a-drawer>
    <div class="buttonBox">
      <template v-if="key != 2">
        <a-button :style="{ marginRight: '15px' }" icon="rollback" @click="handleBack"> 返回引导页 </a-button>
        <a-button :style="{ marginRight: '15px' }" icon="search" @click="handleView"> 预览 </a-button>
        <a-button :loading="btnLoading" type="primary" icon="check" @click="handleSave()"> 完成 </a-button>
      </template>
      <template v-else>
        <a-button :style="{ marginRight: '15px' }" icon="retweet" @click="s_reset()"> 重置 </a-button>
        <a-button :loading="btnLoading" type="primary" icon="check" @click="s_checkNode()"> 完成 </a-button>
      </template>
    </div>
  </div>
</template>

<script>
import { findStepRelation, checkAllStatus } from '@/api/workflow/act_dsn_form_step.js'
import { viewAct_dsn_form_define } from '@/api/workflow/act_dsn_form_define.js'
import { BASE_URL } from '@/utils/request.js'
import { St_step } from '@/enumeration/St_step'
import TimeLimit from '@/views/workflow/Wf_NodeTimeLimit.vue'
import { saveAll } from '@/api/workflow/act_dsn_form_scat.js'

export default {
  data() {
    return {
      btnLoading: false, // 按钮保存状态
      key: '1', // 卡片切换key
      St_step: St_step, // 配置状态枚举
      formDefine: {}, // 流程表单信息
      nodeList: [], // 流程模型节点列表
      processimg: '', // 预览图片路径
      base_url: BASE_URL, // 浏览器url前缀
      loading: false, // 遮罩是否显示
      visible: false, // 抽屉是否可见
      ubordered: false, // 表格边框是否显示
      status_List: {}, // 配置状态枚举下拉数据
      udata: [], // 表格数据
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: (total) => `共${total}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
      },
      ucolumns: [
        {
          title: '序号',
          width: '50px',
          align: 'center',
          fixed: 'left',
          scopedSlots: { customRender: 'serial' },
        },
        {
          title: '环节',
          dataIndex: 'name',
          width: '1',
          sorter: (a, b) => String(a.name).localeCompare(String(b.name)),
          align: 'left',
          scopedSlots: { customRender: 'nameSlot' },
        },
        {
          title: '已配字段数',
          dataIndex: 'fieldnum_',
          width: '1',
          sorter: (a, b) => a.fieldnum_ - b.fieldnum_,
          align: 'center',
        },
        {
          title: '状态',
          dataIndex: 'status_',
          width: '1',
          align: 'center',
          sorter: (a, b) => a.status_.localeCompare(b.status_),
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' },
        },
      ], // 表头
    }
  },
  async created() {
    // 流程图片
    this.viewDefine()
    this.findAct_dsn_form_stepList(this.$route.params.formid)
    // 回显表格页码
    if (this.$route.query.pageIndex != undefined) {
      this.upagination.current = Number(this.$route.query.pageIndex)
    }
  },
  methods: {
    // 重置环节组配置
    s_reset() {
      this.$nextTick(() => {
        this.$refs.NodeScatRef.f_reset()
      })
    },
    // 调用环节组配置
    s_checkNode() {
      this.$nextTick(() => {
        let check = this.$refs.NodeScatRef.f_checkNode()
        // 最后一个环节 islast 设置为true
        check.value.forEach(v => {
          v.islast = 3201
        })
        check.value[check.value.length - 1].islast = 3200
        console.log('环节分组配置', check)
        if (check?.status) {
          saveAll(this.formDefine.id, check.value).then((res) => {
            if (res.code == 0) {
              this.$message.success('保存成功')
            }
          })
        }
      })
    },
    // 打开办结时限抽屉
    showTimeLimit() {
      this.visible = true
      this.$nextTick(() => {
        this.$refs.limitRef.timelimitInit(this.$route.params.formid)
      })
    },
    /**
     * 收回抽屉
     */
    onClose() {
      this.visible = false
    },
    // tab切换事件
    tabChange(key) {
      this.key = key
    },

    // 返回
    handleBack() {
      this.$router.push({ path: `/Wf_FormGuide/${this.$route.params.operation}/${this.$route.params.formid}` })
    },

    // 查看流程定义
    viewDefine() {
      viewAct_dsn_form_define({ formid: this.$route.params.formid }).then((res) => {
        console.log('定义信息', res)
        if (res.code == 0) {
          // 加载图片
          this.processimg = this.base_url + '/flow/viewCharUnpublishedDiagram?modelKey=' + res.data.key_
          this.formDefine = res.data
        }
      })
    },
    /**
     *  查询流程表单环节配置列表
     */
    findAct_dsn_form_stepList(formid) {
      const a = Date.now()
      findStepRelation(formid, 2).then((res) => {
        this.loading = true
        console.log('表格数据:', res)
        res.data &&
          res.data.forEach((v) => {
            if (v.status_ in this.St_step) {
              v.status_ = this.St_step[v.status_].name
            }
          })
        this.udata = res.data || []
        // 如果查询时间太短就给一个0.5秒的加载效果
        const b = Date.now()
        if (b - a < 500) {
          setTimeout(() => {
            this.loading = false
          }, 500)
        } else {
          this.loading = false
        }
      })
    },
    /**
     * 重置查询条件并查询数据
     */
    reQuery() {
      this.queryParam = {}
      this.findAct_dsn_form_stepList(this.queryParam)
    },

    // 翻页、设置页数量时触发，将分页组建的当前页与大小传给后台
    tableChange(pagination) {
      this.upagination = pagination
    },

    /**
     * 进入编辑页面
     */
    handleEdit(record) {
      this.$router.push({
        path: `/Wf_NodeEdit/${this.$route.params.operation}/${record.id}/${this.$route.params.formid}`,
        query: { processName: record.name, pageIndex: this.upagination.current },
      })
    },

    /**
     * 进入预览页面
     */
    handleView() {
      this.$router.push({
        path: `/Wf_NodeView/${this.$route.params.operation}/${this.$route.params.formid}`,
        query: { processName: this.formDefine.name_, pageIndex: this.upagination.current },
      })
    },
    /**
     * 保存数据
     */
    handleSave() {
      this.btnLoading = true
      // 保存并发布
      checkAllStatus(this.$route.params.formid)
        .then((res) => {
          console.log('环节校验', res)
          if (res.code == 0) {
            // res.data = true 则说明校验通过
            if (res.data) {
              let that = this
              this.$confirm({
                title: '操作成功',
                content: `已完成环节配置，是否进行流程发布？`,
                okText: '是',
                okType: 'danger',
                cancelText: '否',
                onOk: () => {
                  this.$router.push({ path: `/Wf_ProcessPublish/${this.formDefine.key_}/${that.$route.params.formid}` })
                },
                onCancel: () => {
                  this.$router.push({
                    path: `/Wf_FormGuide/${that.$route.params.operation}/${that.$route.params.formid}`,
                  })
                },
              })
            } else {
              this.$message.warning('请完成环节配置')
            }
          }
        })
        .finally(() => {
          this.btnLoading = false
        })
    },
  },
  components: {
    TimeLimit,
    NodeScat: () => import('@/views/workflow/Wf_NodeScat.vue'),
  },
}
</script>

<style scoped>
.cardArea_timelimit {
  position: absolute;
  right: 20px;
}
.cardArea {
  background-color: #ffffff;
  padding: 28px;
  min-height: 745px;
}

.cardArea_title {
  display: flex;
  flex-direction: row;
  align-items: center;
  flex-wrap: wrap;
  width: 100%;
}

.cardArea_title_label {
  width: 3px;
  height: 17px;
  background-color: #5b79fb;
}

.cardArea_title_content {
  margin-left: 0.5%;
  font-size: 19px;
  font-family: Source Han Sans CN;
  font-weight: 550;
  color: #232323;
  letter-spacing: 2px;
}

.cardArea_tabs {
  margin-top: 30px;
}

.buttonBox {
  text-align: center;
  margin-top: 30px;
}
.imgBox {
  /* height: 300px; */
  border: 1px solid #eee;
  margin-bottom: 50px;
  display: flex;
  justify-content: center;
}
</style>
